import {
  getBreadCrumbList,
  setTagNavListInLocalstorage,
  // getMenuByRouter,
  getTagNavListFromLocalstorage,
  getHomeRoute,
  getNextRoute,
  routeHasExist,
  routeEqual,
  getRouteTitleHandled,
  localSave,
  localRead
} from '@/libs/util'

import router from '@/router'
import config from '@/config'
// import NotFoundComponent from '@/view/error-page/404'
import { appRouter } from '@/router/routers'

const { homeName } = config

const closePage = (state, route) => {
  const nextRoute = getNextRoute(state.tagNavList, route)
  state.tagNavList = state.tagNavList.filter(item => {
    return !routeEqual(item, route)
  })
  router.push(nextRoute)
}

export default {
  state: {
    breadCrumbList: [],
    tagNavList: [],
    homeRoute: {
      path: '/home',
      name: 'home',
      meta: {
        title: '首页',
        icon: 'md-home'
      }
    },
    local: localRead('local'),
    errorList: [],
    hasReadErrorPage: false,

    showview: false,
    tagsList: [],
    routers: [
      // homeRouter,
      ...appRouter
    ]
    // routers: routers
  },
  getters: {
    errorCount: state => state.errorList.length
  },
  mutations: {
    setBreadCrumb (state, route) {
      state.breadCrumbList = getBreadCrumbList(route, state.homeRoute)
    },
    setHomeRoute (state, routes) {
      console.log('setHomeRoute')
      state.homeRoute = getHomeRoute(routes, homeName)
    },
    setTagNavList (state, list) {
      let tagList = []
      if (list) {
        tagList = [...list]
      } else {
        tagList = getTagNavListFromLocalstorage() || []
      }
      if (tagList[0] && tagList[0].name !== homeName) {
        tagList.shift()
      }
      let homeTagIndex = tagList.findIndex(item => item.name === homeName)
      if (homeTagIndex > 0) {
        let homeTag = tagList.splice(homeTagIndex, 1)[0]
        tagList.unshift(homeTag)
      }
      state.tagNavList = tagList
      setTagNavListInLocalstorage([...tagList])
    },
    closeTag (state, route) {
      let tag = state.tagNavList.filter(item => routeEqual(item, route))
      route = tag[0] ? tag[0] : null
      if (!route) return
      closePage(state, route)
    },
    addTag (state, { route, type = 'unshift' }) {
      // console.log('addTag', route)
      let router = getRouteTitleHandled(route)
      // console.log(router)

      if (!routeHasExist(state.tagNavList, router)) {
        // console.log('route Has not Exist')

        if (type === 'push') {
          state.tagNavList.push(router)
        } else {
          if (router.name === homeName) {
            state.tagNavList.unshift(router)
          } else {
            state.tagNavList.splice(1, 0, router)
          }
        }
        setTagNavListInLocalstorage([...state.tagNavList])
      }
    },
    setLocal (state, lang) {
      localSave('local', lang)
      state.local = lang
    },
    addError (state, error) {
      state.errorList.push(error)
    },
    setHasReadErrorLoggerStatus (state, status = true) {
      state.hasReadErrorPage = status
    },

    setTagsList (state, list) {
      // console.log('setTagsList', list)
      state.tagsList.push(...list)
    },

    addRouters (state, router) {
      state.routers = [...state.routers, ...router]
    }
  },
  actions: {
    addErrorLog ({ commit, rootState }, info) {
      if (!window.location.href.includes('error_logger_page')) {
        commit('setHasReadErrorLoggerStatus', false)
      }
      const {
        user: { token, userId, userName }
      } = rootState
      let data = {
        ...info,
        time: Date.parse(new Date()),
        token,
        userId,
        userName
      }

      switch (info.code) {
        case 401:
          router.push({ name: 'error_401' })
          // 清空登陆状态，跳转到登陆页面
          // this.dispatch('handleFrontLogOut').then(()=>{
          // })
          // console.log(this._vm)
          // 跳转到登陆页面
          // router.push({ name: 'login' })
          break
        case 404:
          router.push({ name: 'error_404' })
          break
        case 500:
          router.push({ name: 'error_500' })
          break
        case 200:
          commit('addError', data)
          this._vm.$Message.error(info.mes)
          break
        default:
          this._vm.$Message.error('请求失败')
          break
      }

      // saveErrorLogger(info).then(() => {
      //   commit('addError', data)
      // })
    }
  }
}
